package com.chushouya.manager.dao.repository;

import com.chushouya.manager.dao.entity.MenuEntity;
import com.chushouya.manager.dao.mapper.MenuEntityMapper;
import com.chushouya.manager.dto.admin.menu.MenuQuery;
import com.general.framework.core.lang.Lists;
import com.general.framework.core.lang.Strings;
import com.general.framework.data.mybatis.BaseRepository;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;

@Repository
public class MenuRepository extends BaseRepository<MenuEntityMapper, MenuEntity, Long> {

    public List<MenuEntity> selectAllMenu(Integer systemType) {
        MenuQuery query = new MenuQuery();
        query.setSystemType(systemType);
        return this.selectByExample(this.buildQueryExample(query));
    }

    public int selectChildMenuCount(Long menuId) {
        Example example = this.buildExample();
        example.and().andEqualTo("parentId", menuId);
        return this.selectCountByExample(example);
    }

    public MenuEntity selectOne(MenuQuery query) {
        return this.selectFirstOneByExample(this.buildQueryExample(query));
    }

    public List<MenuEntity> selectMenuList(MenuQuery query) {
        return this.selectByExample(this.buildQueryExample(query));
    }

    private Example buildQueryExample(MenuQuery query) {
        Example example = this.buildExample();
        if (Strings.isNotEmpty(query.getMenuName())) {
            example.and().andEqualTo("menuName", query.getMenuName());
        }
        if (Objects.nonNull(query.getStatus())) {
            example.and().andEqualTo("status", query.getStatus());
        }
        if (Lists.isNotEmpty(query.getMenuType())) {
            example.and().andIn("menuType", query.getMenuType());
        }
        if (Objects.nonNull(query.getSystemType())) {
            example.and().andEqualTo("systemType", query.getSystemType());
        }
        if (Lists.isNotEmpty(query.getMenuIdList())) {
            example.and().andIn("menuId", query.getMenuIdList());
        }
        if (Objects.nonNull(query.getIdNotEqualTo())) {
            example.and().andNotEqualTo("menuId", query.getIdNotEqualTo());
        }
        example.orderBy("orderNum").asc();
        return example;
    }
}
